package com.feng.zshop.backend.controller;

import com.feng.zshop.backend.dto.ProductDTO;
import com.feng.zshop.backend.service.ProductService;
import com.feng.zshop.backend.service.ProductTypeService;
import com.feng.zshop.backend.vo.ProductVO;
import com.feng.zshop.model.ProductType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Lee
 * @date 2019/2/17
 */
@Controller
@RequestMapping("/backend/product")
public class ProductController {

    @Autowired
    private ProductTypeService productTypeService;

    @Autowired
    private ProductService productService;

    @ModelAttribute(value = "productTypes")
    public List<ProductType> loadProductTypes(){
        return productTypeService.findProductTypeEnable();
    }

    @RequestMapping("/findAll")
    public String findAllProduct(){

        return "productManager";
    }

    @PostMapping("/add")
    public String addProduct(ProductVO productVO, HttpSession session, Model model){
        String uploadPath = session.getServletContext().getRealPath("/WEB-INF/upload");

        try {
            ProductDTO productDTO = new ProductDTO();
            BeanUtils.copyProperties(productVO, productDTO);

            System.out.println("getName()-->" + productVO.getFile().getName());
            productDTO.setInputStream(productVO.getFile().getInputStream());
            productDTO.setFileName(productVO.getFile().getOriginalFilename());
            productDTO.setUploadPath(uploadPath);
            productService.saveProduct(productDTO);

            model.addAttribute("successMsg", "添加成功");
        } catch (Exception e) {
            model.addAttribute("errorMsg", e.getMessage());
        }
        return "forward:findAll";
    }

}
